package com.chiyoyo.rabbitmq.framework.service.impl;

import com.chiyoyo.rabbitmq.framework.annotation.RabbitMq;
import com.chiyoyo.rabbitmq.framework.service.AbstractMQService;
import org.springframework.amqp.core.*;
import org.springframework.amqp.core.BindingBuilder.HeadersExchangeMapConfigurer;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chil
 */
@Service("headersMQService")
public class HeadersMQService extends AbstractMQService {


    @Override
    protected AbstractExchange initExchange(String exchange, RabbitMq rabbitMq) {
        // 初始化Headers类型的Exchange
        return new HeadersExchange(exchange);
    }

    @Override
    protected Binding initBinding(Queue queue, AbstractExchange exchange, String routingKey, RabbitMq rabbitMq) {
        // 初始化与Queue绑定的信息，根据RabbitMq配置构建Headers交换器的绑定规则
        // 创建绑定配置对象
        HeadersExchangeMapConfigurer headersExchangeMapConfigurer = BindingBuilder.bind(queue).to((HeadersExchange) exchange);
        // 获取headers配置信息
        String[] headers = rabbitMq.headers();
        // 构建headers的Map
        Map<String, Object> headerMap = new HashMap<>();
        // 如果配置了按值匹配
        if (rabbitMq.matchValue()) {
            for (int i = 0; i < headers.length; i += 2) {
                String key = headers[i];
                // 确保headers数组的索引是合法的
                Object value = i + 1 > headers.length ? null : headers[i + 1];
                headerMap.put(key, value);
            }
        }
        // 根据匹配所有或任意一个的条件来构建绑定规则
        if (rabbitMq.matchAll()) {
            // 如果同时配置了按值匹配，则使用whereAll进行匹配
            return rabbitMq.matchValue() ? headersExchangeMapConfigurer.whereAll(headerMap).match() : headersExchangeMapConfigurer.whereAll(headers).exist();
        } else {
            // 如果配置了按任意一个匹配，则使用whereAny进行匹配
            return rabbitMq.matchValue() ? headersExchangeMapConfigurer.whereAny(headerMap).match() : headersExchangeMapConfigurer.whereAny(headers).exist();
        }
    }
}

